/**
 * Munges in-place the SVGs in src/wab/client/icons/, which are expected to be
 * exported from Figma with the hard-coded fill color of #050505.  Replaces this
 * with `currentcolor` so that we can dynamically color the icons as we want.
 *
 * Also produces React components for the SVGs.  This is until we upgrade
 * react-scripts, later versions of which support `import {ReactComponent} from
 * "./foo.svg"`.
 */

import fs from "fs";
import glob from "glob";
import Path from "path";
import { capCamelCase } from "../src/wab/shared/common";
import { L } from "../src/wab/shared/core/deps";

async function main() {
  for (const path of glob.sync("src/wab/client/icons/*.svg")) {
    const content = fs
      .readFileSync(path, { encoding: "utf8" })
      .replace(/#050505/g, "currentcolor");
    fs.writeFileSync(path, content, { encoding: "utf8" });
    const filename = Path.basename(path);
    const componentName = capCamelCase(filename.replace(".svg", "")) + "Icon";
    // For some reason, maskType on <mask> React elements is not recognized by
    // React.
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    const jsxified = content
      .replace("<svg", '<svg className="custom-svg-icon"')
      .replace(/\b(clip-path|clip-rule|fill-rule|stroke-width)\b/g, (text) =>
        L.camelCase(text)
      );
    fs.writeFileSync(
      `src/wab/client/components/icons/${componentName}.tsx`,
      `
/**
 * This file was generated by process-svgs.
 */

import React from "react";
import { ReactComponent as Icon } from "../../icons/${filename}";

type SvgProps = JSX.IntrinsicElements["svg"];

export function ${componentName}(props: SvgProps) {
  const className = "custom-svg-icon " + props.className || "";
  return <Icon {...props} className={className} />;
}
      `.trim() + "\n"
    );
  }
}

main();
